import {
  Avatar,
  Button,
  FilledInput,
  FormControl,
  Grid,
  InputLabel,
  MenuItem,
  Paper,
  Select,
  TextField,
  Typography,
} from "@mui/material";
import { Box } from "@mui/system";
import React from "react";
import { useEffect } from "react";
import { useState } from "react";
import provinces from "./regions/province.json";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import cities from "./regions/city.json";
import counties from "./regions/county.json";
import { useContext } from "react";
import { TitleContext } from "../../../router";
import useProfile from "../../../query/useProfile";
import Loading from "../../../components/loading";
import { useSnackbar } from "notistack";
import { DesktopDatePicker } from "@mui/x-date-pickers/DesktopDatePicker";
import { useNavigate } from "react-router-dom";
import { UserContext, UserIdContext, UserProContext } from "../../../App";
import { queryClient } from "../../../query/CustomQueryClient";
import LoadingButton from "../../../components/LoadingButton";
import useUploadAvatar from "../../../query/useUploadAvatar";
import moment from "moment/moment";
import imageCompression from "browser-image-compression";
import useUpdInfo from "../../../query/useUpdInfo";
import useChangePwd from "../../../query/useChangePwd";
import {
  PROFILE_TEACHER_URL,
  UPLOAD_TEACHER_AVATAR_URL,
} from "../../../constants/url";
import MyTextarea from "../../../components/MyTextArea";
const MyTitle = ({ value }) => {
  return (
    <Typography variant="h6" sx={{ marginTop: 2, marginBottom: 1 }}>
      {value}
    </Typography>
  );
};
const fileoptions = {
  maxSizeMB: 1,
  useWebWorker: true,
};
export default function UserSetting() {
  const { enqueueSnackbar } = useSnackbar();
  // const prv
  const [avatar, setAvatar] = useState();
  const user = useContext(UserContext);
  const titleContext = useContext(TitleContext);
  const [avatarFetching, setAvatarFetching] = useState(false);
  const [avatarSuccess, setAvatarSuccess] = useState(false);
  const [oldpwd, setOldpwd] = useState("");
  const [newpwd, setNewpwd] = useState("");
  const [infoSuccess, setInfoSuccess] = useState(false);
  const [pwdSuccess, setPwdSuccess] = useState(false);
  const [proInfo, setProInfo] = useState({
    name: "",
    gender: "",
    grade: "",
    birthday: "",
  });

  useEffect(() => {
    queryClient.clear();
  }, []);
  const userproContext = useContext(UserProContext);

  useEffect(() => {
    titleContext.setnowTitle(2);
  }, []);
  const userId = useContext(UserIdContext);
  const {
    data: avatardata,
    isSuccess: avatarIsSuccess,
    isError: avatarIsError,
    isLoading: avatarIsLoading,
    mutate,
  } = useUploadAvatar();

  const {
    data: pwdData,
    isSuccess: pwdIsSuccess,
    isError: pwdIsError,
    isLoading: pwdIsLoading,
    mutate: pwdMutate,
  } = useChangePwd();

  const {
    isSuccess: infoIsSuccess,
    isError: infoIsError,
    isLoading: infoIsLoading,
    mutate: infoMutate,
  } = useUpdInfo();

  const handleUploadinfo = () => {
    var tmp = proInfo;
    for (var i in tmp) {
      if (tmp[i] == null) delete tmp[i];
      // tmp[i] = tmp[i] !== null ? tmp[i] : "";
    }
    delete tmp.id;
    delete tmp.userId;
    delete tmp.duty;
    delete tmp.pinyin;
    delete tmp.lectureCourse;
    delete tmp.gender;
    delete tmp.email;
    delete tmp.phone;
    infoMutate({
      data: tmp,
      url: PROFILE_TEACHER_URL,
    });
  };

  useEffect(() => {
    if (!avatarIsLoading) setAvatarFetching(false);
  }, [avatarIsLoading]);

  useEffect(() => {
    if (avatarIsSuccess) {
      setAvatarSuccess(true);
      setFile(null);
      setTimeout(() => {
        setAvatarSuccess(false);
      }, 1500);
    }
  }, [avatarIsSuccess]);

  useEffect(() => {
    if (pwdIsSuccess) {
      //
      if (pwdData.data.code === 0) {
        setPwdSuccess(true);

        enqueueSnackbar(pwdData.data.data, { variant: "success" });
        localStorage.removeItem("role");
        localStorage.removeItem("token");
        user.setUser(0);
        navigate("/login/index");
      } else {
        enqueueSnackbar(pwdData.data.message, { variant: "error" });
      }
    }
  }, [pwdIsSuccess]);

  useEffect(() => {
    if (infoIsSuccess) {
      setInfoSuccess(true);
      setTimeout(() => {
        setInfoSuccess(false);
      }, 1500);
    }
  }, [infoIsSuccess]);
  const [file, setFile] = useState();
  
  const handleUpload = async () => {
    if (document.getElementById("trueupload").files[0])
      setFile(document.getElementById("trueupload").files[0]);
    let nowfile;
    if (file) nowfile = file;
    else nowfile = document.getElementById("trueupload")?.files[0];
    if (!nowfile) {
      enqueueSnackbar("请选择图片", { variant: "error" });
      return;
    }

    var ext = nowfile.name.split(".")[1];
    var compressedFile;
    setAvatarFetching(true);
    if (ext != "gif") {
      compressedFile = await imageCompression(nowfile, fileoptions);
    } else compressedFile = nowfile;
    let param = new FormData();
    param.append("file", compressedFile);
    mutate({ data: param, url: UPLOAD_TEACHER_AVATAR_URL });
  };
  const handleUploadPwd = () => {
    if (oldpwd == "" || newpwd == "") {
      enqueueSnackbar("密码不能为空", { variant: "warning" });
      return;
    }
    if (oldpwd == newpwd) {
      enqueueSnackbar("新密码不能和旧密码相同", { variant: "warning" });
      return;
    }
    var pattern1 = /([0-9]+)/;
    var pattern2 = /([a-z]+)/;
    var pattern3 = /([A-Z]+)/;
    if (newpwd.length < 8 || newpwd.length > 20) {
      enqueueSnackbar("新密码长度必须在8到20个字符之间", {
        variant: "warning",
      });

      return;
    }
    //没有数字、大写字母、小写字母时返回false，验证输入的密码不符合规则。
    if (
      !pattern1.exec(newpwd) ||
      !pattern2.exec(newpwd) ||
      !pattern3.exec(newpwd)
    ) {
      enqueueSnackbar("新密码必须包含数字、大写字母和小写字母", {
        variant: "warning",
      });

      //不能有空格、换行、tab缩进等所有的空白
      var pattern4 = /\s+/g;
      if (pattern4.exec(newpwd)) {
        enqueueSnackbar("新密码只能包含数字、大小写字母", {
          variant: "warning",
        });

        return;
      }
      return;
    }

    pwdMutate({ oldPassword: oldpwd, newPassword: newpwd });
  };

  useEffect(() => {
    if (avatarIsError) {
      enqueueSnackbar("动图大小最多2MB哦", { variant: "error" });
    }
  }, [avatarIsError]);
  const navigate = useNavigate();

  useEffect(() => {
    setAvatar(userproContext.userPro.avatar);
    setProInfo(userproContext.userPro);
  }, [userproContext.userPro]);

  const uploadIt = (e) => {
    if (!e.target.files[0]) return;
    setFile(e.target.files[0]);
    //
    const path = window.URL.createObjectURL(e.target.files[0]);
    setAvatar(path);
  };

  const handleChose = () => {
    var evt = new MouseEvent("click", {
      bubbles: false,
      cancelable: true,
      view: window,
    });
    var inputNode = document.getElementById("trueupload");
    inputNode.dispatchEvent(evt);
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <Grid container spacing={2}>
        <Grid item xs={12} md={8}>
          <Paper elevation={2} sx={{ display: "flex" }}>
            <Box sx={{ marginLeft: 10, marginTop: 5, marginBottom: 5 }}>
              <Typography variant="h5">个人设置</Typography>
              <Box sx={{ marginLeft: 5 }}>
                <MyTitle value="姓名" />
                <TextField
                  disabled
                  size="small"
                  id="outlined-required"
                  label="Name"
                  value={proInfo.name}
                />
                {/* {proInfo.name} */}
                <MyTitle value="性别" />
                <TextField
                  size="small"
                  disabled
                  value={proInfo.gender}
                  label="Gender"
                />

                <MyTitle value="学院" />
                <TextField
                  size="small"
                  disabled
                  value={proInfo.college}
                  label="Gender"
                />

                <MyTitle value="职称" />
                <TextField
                  size="small"
                  disabled
                  value={proInfo.title}
                  label="title"
                />
                <MyTitle value="学位" />
                <TextField
                  size="small"
                  // disabled
                  onChange={(e) => {
                    setProInfo({ ...proInfo, degree: e.target.value });
                  }}
                  value={proInfo.degree}
                  label="degree"
                />
                <MyTitle value="研究领域" />
                <TextField
                  size="small"
                  label="researchInterests"
                  onChange={(e) => {
                    setProInfo({
                      ...proInfo,
                      research: e.target.value,
                    });
                  }}
                  value={proInfo.research}
                />

                <MyTitle value="讲授课程" />
                <TextField
                  size="small"
                  label="course"
                  disabled
                  value={proInfo.lectureCourse}
                />
                <MyTitle value="自我介绍" />
                <MyTextarea
                  // size="small"
                  // label="course"
                  change={(e) => {
                    setProInfo({ ...proInfo, introduction: e });
                  }}
                  value={proInfo.introduction}
                />
                <MyTitle value="教育背景" />

                <MyTextarea
                  // size="small"
                  // label="course"
                  change={(e) => {
                    setProInfo({ ...proInfo, educationBackground: e });
                  }}
                  value={proInfo.educationBackground}
                />
              </Box>
              <Box
                sx={{
                  marginTop: 4,
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "center",
                  alignItems: "center",
                  width: "100%",
                }}
              >
                <LoadingButton
                  titler={infoSuccess ? "保存成功" : "保存"}
                  clickr={handleUploadinfo}
                  isFetching={infoIsLoading}
                  isSuccess={infoSuccess}
                />
              </Box>
            </Box>
          </Paper>
        </Grid>
        <Grid item xs={12} md={4}>
          <Paper sx={{ paddingTop: 6 }}>
            <Box
              sx={{
                width: "100%",
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <Box sx={{ maxWidth: "170px", width: "80%" }}>
                <Avatar
                  alt={proInfo.name}
                  sx={{
                    width: "100%",
                    height: "auto",
                    aspectRatio: "1/1",
                  }}
                  src={avatar}
                ></Avatar>
                <form id="uploadForm">
                  <input
                    name="avatar"
                    type="file"
                    id="trueupload"
                    style={{ display: "none" }}
                    onChange={uploadIt}
                    accept="image/png,image/gif,image/jpeg"
                  ></input>
                </form>
              </Box>
              <Box sx={{ marginTop: 2, marginBottom: 3 }}>
                <LoadingButton
                  titlel="保存"
                  showLeft={true}
                  titler={avatarSuccess ? "上传成功" : "选择图片"}
                  clickl={handleUpload}
                  clickr={handleChose}
                  isFetching={avatarFetching}
                  isSuccess={avatarSuccess}
                  litleTitle="可以上传动图哦"
                />
              </Box>
            </Box>
          </Paper>
          <Paper sx={{ marginTop: "50px", padding: "20px" }}>
            <Box>
              <Typography variant="h5">修改密码</Typography>
            </Box>
            <Box sx={{ marginLeft: 8, marginTop: 3 }}>
              <MyTitle value="原密码"></MyTitle>
              <TextField
                label="old password"
                type="password"
                size="small"
                onChange={(e) => {
                  setOldpwd(e.target.value);
                }}
                value={oldpwd}
              />
              <MyTitle value="新密码"></MyTitle>
              <TextField
                label="new password"
                type="password"
                size="small"
                value={newpwd}
                onChange={(e) => {
                  setNewpwd(e.target.value);
                }}
              />
            </Box>
            <Box
              sx={{
                marginTop: 4,
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
                alignItems: "center",
                width: "100%",
              }}
            >
              <LoadingButton
                titler={pwdSuccess ? "保存成功" : "保存"}
                clickr={handleUploadPwd}
                isFetching={pwdIsLoading}
                isSuccess={pwdSuccess}
              />
            </Box>
          </Paper>
        </Grid>
      </Grid>
    </LocalizationProvider>
  );
}
